﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using codewriter;

namespace sqlDALgen.Loaders
{
    public class CustomEntityLoader : IEntityDataLoader
    {
        public TemplateData Load(string name, string schema, string connectionString)
        {
            var data = TemplateData.FromXmlFile(String.Format("{0}.xml", name));

            var entities = data.ResolvePath("entity.from");
            foreach (var entity in entities)
            {
                var table = entity.Value;

                var tableName = table.Value.ToString().Trim();
                if (tableName.IndexOf(".") != -1)
                {
                    schema = tableName.Split('.')[0];
                    if (schema.StartsWith("["))
                        schema = schema.Substring(1, schema.Length - 2);
                    tableName = tableName.Split('.')[1];
                    if (tableName.StartsWith("["))
                        tableName = tableName.Substring(1, tableName.Length - 2);
                }

                table.Add("tables", DbUtil.LoadTableSchema(tableName, schema, connectionString)["tables"]);
            }

            return data;
        }
    }
}
